//
//  WLDownUploadSubController.m
//  WanLian
//
//  Created by muzhuang on 2018/11/4.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLDownUploadSubController.h"
#import "WLDownLoadCenter.h"
#import "WLFileBaseCenter.h"
#import "WLDataBaseManager.h"
#import "WLUpDownloadTaskCell.h"
#import "WLUpDownloadedTaskCell.h"
#import "WLUpLoadCenter.h"
#import "WLDownLoadCenter.h"
#import "NSString+Ext.h"
#import "WLPhotoSubModel.h"
#import "WLFileUpDownLoadModel.h"
#import "WLPhotoLookVController.h"
#import "WLVideoPlayManager.h"
#import "WLFileHandle.h"
#import "WLNoDataCell.h"
#define LIST_STEP 10
@interface WLDownUploadSubController ()<UITableViewDelegate, UITableViewDataSource, WLFileBaseCenterDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *tasksArray;
@property (nonatomic, strong) NSMutableArray *loadedArray;
@property (nonatomic, strong) WLFileBaseCenter *fileHandleCenter;
@property (nonatomic, assign) WLDataBaseModelType dataBaseLoadedModelType;
@property (nonatomic, assign) WLDataBaseModelType dataBaseLoadModelType;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) BOOL notHasNewData;
@property (nonatomic, assign) NSInteger startIndex;
@property (nonatomic, strong) WLVideoPlayManager *player;
@property (nonatomic, strong) NSIndexPath *curDeleteIndexPath;
@property (nonatomic, assign) NSInteger totalCount;

@end

@implementation WLDownUploadSubController
-(WLDataBaseModelType)dataBaseLoadModelType {
    if (self.controllerType == WLControllerTypeUpload) {
        _dataBaseLoadModelType = WLDataBaseModelTypeUpload;
    } else {
        _dataBaseLoadModelType = WLDataBaseModelTypeDownload;
    }
    return _dataBaseLoadModelType;
}
-(WLDataBaseModelType)dataBaseLoadedModelType {
    
    if (self.controllerType == WLControllerTypeUpload) {
        _dataBaseLoadedModelType = WLDataBaseModelTypeUploaded;
    } else {
        _dataBaseLoadedModelType = WLDataBaseModelTypeDownloaded;
    }
    return _dataBaseLoadedModelType;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.fileHandleCenter.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.fileHandleCenter.delegate = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatTableView];
    self.fileHandleCenter.delegate = self;
    self.pageNum = 1;
    [self requestLoadedData];
    [self reloadUI];
}

- (void)reloadUI {
    
    [self.tasksArray removeAllObjects];
    [self.tasksArray addObjectsFromArray:[self.fileHandleCenter getTasksArray]];
    [self.tableView reloadData];
}
- (void)requestLoadedData {
    if (self.pageNum < 1) {
        return;
    }
    self.totalCount = [self getTotalCountWithoModelType:self.dataBaseLoadedModelType];
    NSArray *dataArr = [self getDataFromIndex:(self.pageNum -1)*LIST_STEP step:LIST_STEP modelType:self.dataBaseLoadedModelType];
//    [self addLoadedModelsInOrder:dataArr];
    if (self.pageNum == 1) {
        [self.loadedArray removeAllObjects];
    }
    [self.loadedArray addObjectsFromArray:dataArr];
    [self.tableView.mj_header endRefreshing];
    if (self.loadedArray.count < self.totalCount) {
        self.notHasNewData = NO;
        [self.tableView.mj_footer endRefreshing];
    } else {
        self.notHasNewData = YES;
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    [self.tableView reloadData];
//    if (dataArr.count < 10) {
//        self.notHasNewData = YES;
//        [self.tableView.mj_footer endRefreshingWithNoMoreData];
//    } else {
//        self.notHasNewData = NO;
//        [self.tableView.mj_footer endRefreshing];
//    }
}
//- (void)addLoadedModelsInOrder:(NSArray *)dataArr {
//    NSInteger startPoint = self.loadedArray.count;
//    for (id object in dataArr) {
//        [self.loadedArray insertObject:object atIndex:startPoint];
//    }
//}
- (NSArray *)getAllDataWithModelType:(WLDataBaseModelType)modelType {
    
    return [[WLDataBaseManager shareInstance] queryTotalListWithTableName:[WLFileUpDownLoadModel getTableNameWithModelType:modelType] className:[WLFileUpDownLoadModel class]];
}
- (NSArray *)getDataFromIndex:(NSInteger)startIndex step:(NSInteger)step modelType:(WLDataBaseModelType)modelType {
    if (modelType == WLDataBaseModelTypeUploaded) {
        return [[WLDataBaseManager shareInstance] queryClassName:[WLFileUpDownLoadModel class] tableName:[WLFileUpDownLoadModel getTableNameWithModelType:modelType] fromIndex:startIndex step:step orderBy:@"bg_createTime" desc:YES];
    } else if (modelType == WLDataBaseModelTypeDownloaded) {
        NSDictionary *conditionDict = @{@"showInCompleteList":@YES};
        return [[WLDataBaseManager shareInstance] queryClassName:[WLFileUpDownLoadModel class] tableName:[WLFileUpDownLoadModel getTableNameWithModelType:modelType] condition:conditionDict fromIndex:startIndex step:step orderBy:@"bg_createTime" desc:YES];
    }
    return [NSArray array];
}
- (NSInteger)getTotalCountWithoModelType:(WLDataBaseModelType)modelType {
    NSDictionary *conditionDict = nil;
    if (modelType == WLDataBaseModelTypeDownloaded) {
        conditionDict = @{@"showInCompleteList":@YES};
    }
    return [[WLDataBaseManager shareInstance] countOfTableName:[WLFileUpDownLoadModel getTableNameWithModelType:modelType] condictionDict:conditionDict];
}
#pragma mark -  WLFileBaseCenterDelegate
- (void)updateNetSpeed:(NSString *)netSpeed withIndex:(NSInteger)index {
    WLUpDownloadTaskCell *taskCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [taskCell updateRealTimeSpeed:netSpeed];
}
- (void)updateUI {
    [self reloadUI];
}
- (void)dealWithProcess:(float)progress receivedSize:(NSInteger)receivedSize expectedSize:(NSInteger)expectedSize index:(NSInteger)index {
    WLUpDownloadTaskCell *taskCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [taskCell updateProgressWithProgress:progress receivedSize:receivedSize expectedSize:expectedSize];
    
}
- (void)updateProgress:(float)progress index:(NSInteger)index {
    WLUpDownloadTaskCell *taskCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [taskCell updateProgressWithProgress:progress];
}
- (void)didDeleteTaskWithIndexPath:(NSIndexPath *)indexPath {
    [self reloadUI];
}
- (void)didCompleteTaskWithModel:(WLFileUpDownLoadModel *)model {
    self.pageNum = 1;
    [self requestLoadedData];
    [self reloadUI];
    
}
- (void)didFailTaskWithIndex:(NSInteger)index {
    
    [self reloadUI];
}
- (void)didStartTastWithIndex:(NSInteger)index {
    [self reloadUI];
    WLUpDownloadTaskCell *taskCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [taskCell configStartState];
}

- (void)creatTableView
{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_width, Screen_height -EQ_StatusBarAndNavigationBarHeight - 40) style:UITableViewStylePlain];
    self.tableView.backgroundColor = rgba(249, 249, 249, 1);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.scrollEnabled = YES;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    WLWkSelf
    self.tableView.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.pageNum = 1;
        [weakSelf requestLoadedData];
    }];    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}
- (void)footerRefresh {
    if (self.notHasNewData == NO) {
        self.pageNum ++;
        [self requestLoadedData];
    }
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        if (self.tasksArray.count == 0) {
            return 1;
        }
        return self.tasksArray.count;
    } else if (section == 1) {
        if (self.loadedArray.count == 0) {
            return 1;
        }
        return self.loadedArray.count;
    }
    return 0;
}
- (NSString *)noDataViewIsLoaded:(BOOL)isLoaded isUpload:(BOOL)isUpload {
    NSString *text = nil;
    if (isLoaded == YES) {
        text = @"这里是空的，还没有完成的内容哦~";
    } else {
        if (isUpload == YES) {
            text = @"这里是空的，还没有上传内容哦~";
        } else {
            text = @"这里是空的，还没有下载内容哦~";
        }
    }
    return text;
}
- (WLNoDataCell *)getNoDataCellIsLoaded:(BOOL)isLoaded tableView:(UITableView *)tableView {
    
    WLNoDataCell *nodataCell = [WLNoDataCell createCellWithTableView:tableView cellIndetifier:@"WLNoDataCell"];
    WLNoDataModel *model = [[WLNoDataModel alloc] init];
    model.title = [self noDataViewIsLoaded:isLoaded isUpload:(self.controllerType == WLControllerTypeUpload)];
    nodataCell.model = model;
    return nodataCell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            if (self.tasksArray.count == 0) {
                return [self getNoDataCellIsLoaded:NO tableView:tableView];
            }
        }
        WLUpDownloadTaskCell *taskCell = [WLUpDownloadTaskCell createCellWithTableView:tableView cellIndetifier:@"WLUpDownloadTaskCell"];
        WLFileUpDownLoadModel *model = [self.tasksArray objectAtIndex:indexPath.row];
        WLWkSelf
        taskCell.canbeStartBlock = ^BOOL() {
            return [weakSelf.fileHandleCenter isTaskCanBeStart:model];
        };
        taskCell.actionBlock = ^(BOOL isStart) {
            if (isStart == YES) {
                [weakSelf.fileHandleCenter continueTaskWithIndexPath:indexPath];
            } else {
                [weakSelf.fileHandleCenter pauseTaskWithIndexPath:indexPath];
            }
        };
        taskCell.model = model;
        return taskCell;
    } else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            if (self.loadedArray.count == 0) {
                return [self getNoDataCellIsLoaded:YES tableView:tableView];
            }
        }
        WLUpDownloadedTaskCell *loadedTaskCell = [WLUpDownloadedTaskCell createCellWithTableView:tableView cellIndetifier:@"WLUpDownloadedTaskCell"];
        WLFileUpDownLoadModel *model = [self.loadedArray objectAtIndex:indexPath.row];
        loadedTaskCell.model = model;
        return loadedTaskCell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 68;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0) {
        return;
    }
    if (self.loadedArray.count == 0) {
        return;
    }
    WLFileUpDownLoadModel *model = [self.loadedArray objectAtIndex:indexPath.row];
    if (model.fileType == SPFileTypePhoto) {
        WLPhotoSubModel *fileModel = [[WLPhotoSubModel alloc] init];
        fileModel.fileName = model.fileName;
        fileModel.fileURL = model.fileURL;
        fileModel.localIdentifier = model.localIdentifier;
        WLPhotoLookVController *photoController = [[WLPhotoLookVController alloc] init];
        photoController.isLocal = YES;
        photoController.photoModel = fileModel;
        [self.navigationController pushViewController:photoController animated:YES];
    } else {
        if (_player == nil) {
            _player = [[WLVideoPlayManager alloc] init];
            _player.currentController = self.parentViewController;
        }
        if (model.mediaLocalURL) {
            [_player openmovieWithLocalMediaURL:model.mediaLocalURL];
        } else {
            [_player openmovieWithLocal:model.fileURL.path];
        }
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    UILabel *label = [[UILabel alloc] init];
    NSString *result = nil;
    if (section == 0) {
        if (self.controllerType == WLControllerTypeUpload) {
            result = [NSString stringWithFormat:@"上传任务(%lu)", (unsigned long)self.tasksArray.count];
        } else {
            result = [NSString stringWithFormat:@"下载任务(%lu)", (unsigned long)self.tasksArray.count];
        }
    } else if (section == 1) {
        result = [NSString stringWithFormat:@"已完成(%lu)", (unsigned long)self.totalCount];
    }
    label.text = result;
    label.textColor = RGBA(102, 102, 102, 1);
    view.backgroundColor = RGBA(250, 250, 250, 1);
    label.font = [UIFont systemFontOfSize:14];
    label.frame = CGRectMake(16, 0, 200, 48);
    [view addSubview:label];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 48;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *result = nil;
    if (section == 0) {
        if (self.controllerType == WLControllerTypeUpload) {
            result = [NSString stringWithFormat:@"上传任务(%lu)", (unsigned long)self.tasksArray.count];
        } else {
            result = [NSString stringWithFormat:@"下载任务(%lu)", (unsigned long)self.tasksArray.count];
        }
    } else if (section == 1) {
        result = [NSString stringWithFormat:@"已完成(%lu)", (unsigned long)self.loadedArray.count];
    }
    return result;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (self.tasksArray.count > 0) {
            return YES;
        } else {
            return NO;
        }
    } else if (indexPath.section == 1){
        if (self.loadedArray.count > 0) {
            return YES;
        } else {
            return NO;
        }
    }
    return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewCellEditingStyleDelete;
    
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return @"取消任务";
    } else {
        return @"删除";
    }
    
}

/**.点击删除的实现。特别提醒：必须要先删除了数据，才能再执行删除的动画或者其他操作，不然会引起崩溃。*/
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    self.curDeleteIndexPath = indexPath;
    if (indexPath.section == 0) {
        NSArray *taskArr = [self.fileHandleCenter getTasksArray];
        if (indexPath.row >=0 && indexPath.row < taskArr.count) {
            WLFileUpDownLoadModel *model = taskArr[indexPath.row];
            [self confirmDeleteActionWithDownloadType:!model.isUpLoad];
        }
    } else if (indexPath.section == 1){
        WLFileUpDownLoadModel *model = self.loadedArray[indexPath.row];
        NSError *error = nil;
//        if (model.isUpLoad == NO) {
        [WLFileHandle removeItemAtPath:model.fileURL.path error:&error];
//        }
//        if (!error) {
            [self.fileHandleCenter deleteDataBaseWithModel:model];
            self.totalCount = [self getTotalCountWithoModelType:self.dataBaseLoadedModelType];
            [self.loadedArray removeObjectAtIndex:indexPath.row];
            [self.tableView reloadData];
            [SVProgressHUD showAndAutoCloseWithStatus:@"删除成功" delayTime:1.f];
//        } else {
//            [SVProgressHUD showAndAutoCloseWithStatus:@"删除失败" delayTime:1.f];
//        }
    }
}
- (void)confirmDelete {
    NSIndexPath *indexPath = self.curDeleteIndexPath;
    if (!indexPath) {
        return;
    }
    [self.fileHandleCenter deleteTaskWithIndexPath:indexPath];
    self.curDeleteIndexPath = nil;
}
- (void)confirmDeleteActionWithDownloadType:(BOOL)isDownload
{
    NSString *message = @"是否取消该上传任务?";
    if (isDownload == YES) {
        message = @"是否取消该下载任务?";
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    WLWkSelf
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf confirmDelete];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (WLFileBaseCenter *)fileHandleCenter {
    if (_fileHandleCenter == nil) {
        if (self.controllerType == WLControllerTypeDownLoad) {
            _fileHandleCenter = [WLDownLoadCenter shareInstance];
        } else {
            _fileHandleCenter = [WLUpLoadCenter shareInstance];
        }
    }
    return _fileHandleCenter;
}




delay_property_impl(NSMutableArray, loadedArray)
delay_property_impl(NSMutableArray, tasksArray)
@end
